package com.aestheticshare.main;

import java.net.URI;
import java.net.URISyntaxException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.Extra;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.ViewById;

@SuppressLint("SetJavaScriptEnabled")
@EActivity(R.layout.activity_popup_web)
@NoTitle
public class PopupWebActivity extends Activity {
	@Extra("url") String url;
	@ViewById(R.id.webViewPopup) WebView webView;
	@ViewById(R.id.progressBar) ProgressBar progressBar;
	@ViewById(R.id.popupWebCloseBtn) ImageButton closeBtn;
	
	public static void popup(Activity act, String url, int requestCode){
		Intent intent = new Intent(act, PopupWebActivity_.class);
		intent.putExtra("url", url);
		act.startActivityForResult(intent, requestCode);
	}
	
	
	@AfterViews
	void initialize(){
		
		EasyTracker.getInstance().setContext(this);
		
		closeBtn.setOnTouchListener(Utils.IMAGE_BUTTON_ONCLICK_EFFECT_TOUCH_LISTENER);

		
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				progressBar.setVisibility(View.VISIBLE);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				progressBar.setVisibility(View.GONE);				
			}

			@Override
			public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
				if( (!url.startsWith("result:")) && (!url.startsWith("close:"))){
					super.doUpdateVisitedHistory(view, url, isReload);					
				}
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView webView, String url) {
				Log.i("popup webview load url:\n", url);
				try {
					URI uri = new URI(url);
					if(uri.getScheme().equals("sys") && uri.getAuthority().equals("cmd") && (uri.getPath().equals("/result") || uri.getPath().equals("/close"))){
						Intent intent = new Intent();
						String[] params = uri.getQuery().split("&");
						for (String p : params) {
							String[] pair = p.split("=");
							intent.putExtra(pair[0], pair.length == 1 ? "" : pair[1]);						
						}
						PopupWebActivity.this.setResult(Activity.RESULT_OK, intent);
						if(uri.getPath().equals("/close")){
				    		finish();
						}
					}else{
						webView.loadUrl(url);
					}
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
				return true;
			}
			
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Toast.makeText(getApplication(), R.string.msg_on_received_error, Toast.LENGTH_LONG).show();
		    	PopupWebActivity.this.setResult(Activity.RESULT_CANCELED);
				finish();
			}

		});
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onCloseWindow(WebView window) {
	    		finish();
			}
			@Override
			public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
				Toast.makeText(getApplication(), message, Toast.LENGTH_LONG).show();
				result.confirm();
				return true;
			}
			@Override
			public boolean onConsoleMessage(ConsoleMessage consoleMessage){
				Log.i("webview Popup", consoleMessage.message());
				return true;
			}
		});
		
		if(url != null){
			Log.i("popup url:", url);
			webView.loadUrl(url);			
		}
	}
	
	@Click(R.id.popupWebCloseBtn)
	void onCloseBtnClick(){
    	PopupWebActivity.this.setResult(Activity.RESULT_CANCELED);
		finish();		
	}
	
	@Override
	protected void onStart() {
		EasyTracker.getInstance().activityStart(this);
		super.onStart();
	}

	@Override
	protected void onStop() {
		EasyTracker.getInstance().activityStop(this);
		super.onStop();
	}

    @Override
	public void onBackPressed() {
    	PopupWebActivity.this.setResult(Activity.RESULT_CANCELED);
		finish();
	}
}
